/*global jQuery, localStorage, md5, Blob, URL, CSV*/
var CollectReqInfo = (function ($, ns) {
    function inArray(needle, haystack) {
        for (var i = 0, l = haystack.length; i < l; i += 1) {
            if (needle === haystack[i]) {
                return true;
            }
        }
        return false;
    }

    function tidy(lines) {
        var pattern  = /^(\d+(、|\.|）|\))?|-|l) */,
            newLines = [];
        for (var i = 0, l = lines.length; i < l; i += 1) {
            if (pattern.test(lines[i])) {
                newLines.push(lines[i]);
            } else {
                break;
            }
        }
        return newLines;
    }

    function parseJD(text) {
        var seperators = {
            'responsibilities': [
                '职位描述',
                '岗位职责',
                '工作职责',
                '具体职责',
                '岗位描述',
                '职责描述',
                '主要工作职能 ：',
                '入职要求 ：',
                '主要职责',
                '职责',
                '您的工作',
                '职务范围',
                '(一)岗位描述',
                '工作内容',
                '职位内容',
                '【岗位职责】',
                'Work Duty/ 工作职责',
                '工作描述（汽车延保部）',
                'Job Duty',
                'Main Requierment',
                'Key Responsibility',
                'Main Responsibility',
                'Key Deliverables',
                'Job Requirement',
                'Job Responsibility/工作职责',
                'Job responsibilities:',
                'Job Responsibilities',
                'Key Deliverables'
            ],
            'requirements': [
                '任职要求',
                '岗位要求',
                '【任职要求】',
                '任职资格的具体描述',
                '任职资格条件',
                '(三)公司待遇',
                '(二)职位要求',
                '相关要求',
                '任职资格',
                '职位要求',
                '入职条件',
                '任职条件',
                '优先考虑',
                '能力要求',
                '我们对您的期望',
                '招聘条件',
                '要求',
                '工作描述',
                '必要经验',
                '岗位需求',
				'岗位资格要求',
                'Job Requirement',
                'Main Duty',
                'Required Experience & Skills',
                'Job Requirements',
                'Job Description',
                'Critical Competencies',
                'Required Experience & Skills',
                'Experience/Technical Knowledge',
                'Profile Requirements',
                'Critical Competencies',
                'Experience/Technical Knowledge',
                'Profile Requirements',
                'Job requirements',
                '任职要求/Job Requirement'
            ]
        };

        function identifySeperator(line) {
            line = line.replace(/：|:/g, '');
            for (var key in seperators) {
                if (inArray(line, seperators[key])) {
                    return key;
                }
            }
        }

        var result = {
            responsibilities: [],
            requirements: []
        };

        var i, len, seperator, sp;

        text = text.trim().split('\n');
        len  = text.length;

        for (i = 0; i < len; i += 1) {
            text[i] = text[i].trim();
        }

        for (i = 0; i < len; i += 1) {
            sp = identifySeperator(text[i]);
            if (sp) {
                seperator = sp;
            } else if (text[i] && seperator) {
                result[seperator].push(text[i]);
            }
        }

        result.responsibilities = tidy(result.responsibilities);
        result.requirements     = tidy(result.requirements);

        return result;
    }

    function resetLocalStorage() {
        localStorage.cri = '{"total":0,"items":[["招聘网站","所属公司","职位名称","招聘人数","工作时间","职位类别","工作地点","岗位职责","任职要求"]],"hashes":{}}';
    }

    function saveStringToLocalFile(string, filename) {
        var b    = new Blob([string], {type: 'text/plain'}),
            link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");

        link.href     = URL.createObjectURL(b);
        link.download = filename;

        var e = document.createEvent('MouseEvents');
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        link.dispatchEvent(e);
    }

    ns.init = function ($container, reqInfo) {
        $container.append([
            '<form class="form-horizontal" id="req-info-form">',
            '   <legend>收集职位信息</legend>',
            '   <div class="control-group">',
            '       <label class="control-label">招聘网站:</label>',
            '       <div class="controls">',
            '           <input type="text" id="cri-jobboard" readonly="true" />',
            '       </div>',
            '   </div>',
            '   <div class="control-group">',
            '       <label class="control-label">所属公司:</label>',
            '       <div class="controls">',
            '           <input type="text" id="cri-entity" />',
            '       </div>',
            '   </div>',
            '   <div class="control-group">',
            '       <label class="control-label">职位名称:</label>',
            '       <div class="controls">',
            '           <input type="text" id="cri-title" />',
            '       </div>',
            '   </div>',
            '   <div class="control-group">',
            '       <label class="control-label">招聘人数:</label>',
            '       <div class="controls">',
            '           <input type="text" id="cri-headcount" />',
            '       </div>',
            '   </div>',
            '   <div class="control-group">',
            '       <label class="control-label">工作时间:</label>',
            '       <div class="controls">',
            '           <input type="text" id="cri-workSchedule" />',
            '       </div>',
            '   </div>',
            '   <div class="control-group">',
            '       <label class="control-label">职位类别:</label>',
            '       <div class="controls">',
            '           <input type="text" id="cri-category" />',
            '       </div>',
            '   </div>',
            '   <div class="control-group">',
            '       <label class="control-label">工作地点:</label>',
            '       <div class="controls">',
            '           <input type="text" id="cri-location" />',
            '       </div>',
            '   </div>',
            '   <div class="control-group">',
            '       <label class="control-label">岗位职责:<span class="label label-important" id="cri-responsibilities-count">0</span></label>',
            '       <div class="controls">',
            '           <textarea id="cri-responsibilities" rows="10" style="width: 90%;"></textarea>',
            '       </div>',
            '   </div>',
            '   <div class="control-group">',
            '       <label class="control-label">任职要求:<span class="label label-important" id="cri-requirements-count">0</span></label>',
            '       <div class="controls">',
            '           <textarea id="cri-requirements" rows="10" style="width: 90%;"></textarea>',
            '       </div>',
            '   </div>',
            '   <div class="control-group" style="text-align:right;margin-right:17px;">',
            '       <button type="button" id="cri-clear" class="btn btn-danger">清空</button>',
            '       <button type="button" id="cri-download" class="btn btn-success">下载</button>',
            '       <button type="button" id="cri-save" class="btn btn-primary">保存</button>',
            '   </div>',
            '   <div style="text-align:right;margin-right:17px;">',
            '       已收集 <span class="label label-success" id="cri-total">0</span> 个职位',
            '   </div>',
            '</form>'
        ].join(''));

        ['jobboard', 'entity', 'title', 'headcount', 'workSchedule', 'category', 'location', 'JD'].forEach(function (key) {
            if (!reqInfo.hasOwnProperty(key)) {
                reqInfo[key] = '';
            }
        });

        var result = parseJD(reqInfo.JD);

        ['jobboard', 'entity', 'title', 'headcount', 'workSchedule', 'category', 'location'].forEach(function (key) {
            $('#cri-' + key).val(reqInfo[key]);
        });
        $('#cri-responsibilities').val(result.responsibilities.join('\n'));
        $('#cri-requirements').val(result.requirements.join('\n'));
        $('#cri-responsibilities-count').html(result.responsibilities.length);
        $('#cri-requirements-count').html(result.requirements.length);

        var cri;
        if (localStorage.cri === undefined) {
            $('#cri-total').text(0);
        } else {
            cri = JSON.parse(localStorage.cri);
            $('#cri-total').text(cri.total);
        }

        $('#cri-save').click(function () {
            $(this).attr('disabled', true);
            if (localStorage.cri === undefined) {
                resetLocalStorage();
            }
            var cri = JSON.parse(localStorage.cri);
            var reqInfo = [];
            ['jobboard', 'entity', 'title', 'headcount', 'workSchedule', 'category', 'location', 'responsibilities', 'requirements'].forEach(function (key) {
                reqInfo.push($('#cri-' + key).val());
            });
            var hash = md5(reqInfo.toString());
            if (cri.hashes[hash] && !confirm('此职位已收集过,确定还要保存吗?')) {
                $(this).attr('disabled', false);
                return;
            }
            cri.total += 1;
            cri.items.push(reqInfo);
            cri.hashes[hash] = 1;
            $('#cri-total').text(cri.total);
            localStorage.cri = JSON.stringify(cri);
            $(this).html('已保存');
        });

        $('#cri-clear').click(function () {
            resetLocalStorage();
            location.reload();
        });

        $('#cri-download').click(function () {
            $(this).attr('disabled', 'disabled')
                   .html('下载已开始...');
            if (localStorage.cri === undefined) {
                resetLocalStorage();
            }
            var cri = JSON.parse(localStorage.cri);
            saveStringToLocalFile(CSV.arrayToCsv(cri.items), 'req.csv');
        });
    };

    return ns;
})(jQuery, {});
